<?php
namespace app\demo\controller;

use app\model\book\BookModel;
use app\model\book\OrderModel;
use think\facade\Db;
use think\facade\Request;
class Model extends Base
{

    public function index()
    {
        echo("tp6 测试");
    }

    // 书列表
    private function bookList() {
        $book = new BookModel();
        $list = $book->getList();   // 效率高
        $list = $book->getAppendList(); // 效率低
        pp($list);
    }

    // 模型查询订单列表, 四层到商品分类
    private function orderList() {
        $order = new OrderModel();
        $list = $order->listFull();
        return successReturn($list);
    }

    // mysql事务DEMO, 模拟转账
    private function transTest()
    {
        $amount = 1000;
        try {
            $whereUser1 = [
                ['id','=',14]
            ];
            $whereUser2 = [
                ['id','=',15]
            ];

            Db::startTrans();
//            $user1 = Db::table('bank')->where($whereUser1)->field('id,user_name,balance')->find(); // 不加锁
            $user1 = Db::table('bank')->where($whereUser1)->lock(true)->field('id,user_name,balance')->find(); // 加锁
            usleep(1000*100); // 模拟 100 毫秒处理其他逻辑
            if($user1['balance'] >= $amount) {
                Db::table('bank')->where($whereUser1)->dec('balance',$amount)->update();
                echo('用户1扣除余额成功!');
//                $whereUser2 = $whereUser1[0]; // 制造报错
                Db::table('bank')->where($whereUser2)->inc('balance',$amount)->update();
                echo('用户2增加余额成功!');
            }else {
                return errorReturn('用户1余额不足','转账失败!');
            }

            Db::commit();
        } catch (\Exception $e) {
            catchException($this->cmd,$e);
            Db::rollback();
            return errorReturn($e->getMessage(),'转账失败!');
        }
        return successReturn('','转账成功!');
    }

    // 模拟转账, 重置数据
    private function resetData()
    {
        $amount = input('param.amount',1000);
        try {
            Db::table('bank')->where('id','in',[14,15])->update(['balance'=>$amount]);
        } catch (\Exception $e) {
            return errorReturn($e->getMessage(),'转账失败!');
        }
        return successReturn('','重置成功!');
//        return successReturn('Hello'); //
    }

    // 查看转账前数据
    private function infoList()
    {
        try {
            $list = Db::table('bank')->where('id','in',[14,15])->select()->toArray();
        } catch (\Exception $e) {
            return errorReturn($e->getMessage(),'操作异常!');
        }
        pp($list);
    }

}
